/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package semanticsearch.util.sql;

import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Pavithre
 */
public class SQLOperation {

    /**
     * Get classes related to
     * <code>keyWard</code>
     *
     * @param keyWord
     * @return
     */
    public ArrayList<String> getClasses(ArrayList<String> searchWordList) {

        // xxx
//        keyWord = "mm";

        String keyWord;
        MySqlConnection mySqlCon = new MySqlConnection();
        ArrayList<String> words = new ArrayList<String>();
        ArrayList<String> classIDList = new ArrayList<String>();

        Connection con = mySqlCon.openConnection();

        try {

            Statement stmt;
            ResultSet rsClassesID, rsWords;

            stmt = con.createStatement();
            
            // Add initial list to result list
            words = (ArrayList<String>)searchWordList.clone();

            for (int j = 0; j < searchWordList.size(); j++) {
                
                keyWord = searchWordList.get(j);

                // Get classes of the key word.
                rsClassesID = stmt.executeQuery("select class_id from words where word = '" + keyWord + "'");

                String classID;
                while (rsClassesID.next()) {

                    classID = rsClassesID.getString(1);
                    
                    String[] tempList;
                    if (classID.contains(",")) {
                        tempList = classID.split(",");
                        
                        for (int i = 0; i < tempList.length; i++) {
                            
                            classIDList.add(tempList[i]);
                        }
                        
                    }else{
                        classIDList.add(classID);
                    }
//                    System.out.println(classID);
                    
                }

                // Get wards belongs to those classes
                for (int i = 0; i < classIDList.size(); i++) {

                    rsWords = stmt.executeQuery("select word from words where class_id='" + classIDList.get(i) + "'");

                    while (rsWords.next()) {

                        words.add(rsWords.getString(1));
//                        System.out.println(rsWords.getString(1));
                    }
                }
            }

        } catch (SQLException ex) {

            Logger.getLogger(SQLOperation.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            mySqlCon.closeConnection();
            return words;
        }
    }

    public static void main(String[] args) {

        SQLOperation sql = new SQLOperation();
        sql.getClasses(null);
    }
}
